<template>
  <el-card>
    <Category :scene="scene"></Category>
  </el-card>
  <el-card style="margin: 10px 0">
    <div v-show="scene === 0">
      <el-button
        type="primary"
        icon="Plus"
        :disabled="categoryStore.categoryIdObj.category3Id ? false : true"
        @click="addAttr"
      >
        添加属性
      </el-button>
      <el-table border :data="attrData" style="margin: 10px 0">
        <el-table-column
          type="index"
          label="序号"
          width="80px"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="attrName"
          label="属性名称"
          width="120px"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值" align="center">
          <template #="{ row }">
            <el-tag
              style="margin: 5px"
              v-for="item in row.attrValueList"
              :key="item.id"
              type="success"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px" align="center">
          <template #="{ row }">
            <el-button
              type="primary"
              icon="Edit"
              size="small"
              @click="updateAttr(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除该${row.attrName}属性吗?`"
              width="250px"
              @confirm="removeAttrValue(row.id)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete" size="small"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div v-show="scene === 1">
      <el-form inline label-width="80px">
        <el-form-item label="属性名称">
          <el-input
            v-model="attrParms.attrName"
            placeholder="请输入属性名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        @click="addAttrValue"
        :disabled="!attrParms.attrName"
        type="primary"
        icon="Plus"
      >
        添加属性值
      </el-button>
      <el-button @click="cancel">取消</el-button>
      <el-table :data="attrParms.attrValueList" border style="margin: 10px 0">
        <el-table-column
          type="index"
          label="序号"
          width="80px"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-input
              :ref="(vc: any) => (inputArr[$index] = vc)"
              @blur="checkRepeat(row, $index)"
              v-model="row.valueName"
              placeholder="请输入属性值名称"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ $index }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="attrParms.attrValueList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        @click="save"
        :disabled="attrParms.attrValueList.length < 1"
      >
        保存
      </el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue'
import {
  reqAttrInfo,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from '@/api/product/attr'
import useCategoryStore from '@/store/modules/category'
import type {
  attrResponseData,
  attrList,
  attr,
  attrValue,
} from '@/api/product/attr/types'
import { ElMessage } from 'element-plus'

let attrData = ref<attrList>([])
let scene = ref(0)
let attrParms = reactive<attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
})
// 存储属性值input实例元素
let inputArr = ref<any>([])

const categoryStore = useCategoryStore()
watch(
  () => categoryStore.categoryIdObj.category3Id,
  () => {
    if (!categoryStore.categoryIdObj.category3Id) return
    getAttrList()
  },
)

onBeforeUnmount(() => {
  categoryStore.$reset()
})

// 获取属性列表
async function getAttrList() {
  const {
    categoryIdObj: { category1Id, category2Id, category3Id },
  } = categoryStore
  console.log(category1Id, category2Id, category3Id, 'categoryIdObj')
  const res: attrResponseData = await reqAttrInfo(
    category1Id,
    category2Id,
    category3Id,
  )
  if (res.code === 200) {
    attrData.value = res.data
  }
}
async function removeAttrValue(id: any) {
  let res = await reqDeleteAttr(id)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getAttrList()
  } else {
    ElMessage.error('删除失败')
  }
}

function addAttr() {
  scene.value = 1
  Object.assign(attrParms, {
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.categoryIdObj.category3Id,
  })
}

function updateAttr(row: attr) {
  scene.value = 1
  Object.assign(attrParms, JSON.parse(JSON.stringify(row)))
}

function cancel() {
  scene.value = 0
}

function addAttrValue() {
  attrParms.attrValueList.push({
    valueName: '',
  })
  nextTick(() => {
    inputArr.value[inputArr.value.length - 1].focus()
  })
}

async function save() {
  let res = await reqAddOrUpdateAttr(attrParms)
  if (res.code === 200) {
    scene.value = 0
    ElMessage.success(attrParms.id ? '修改成功' : '添加成功')
    getAttrList()
  } else {
    ElMessage.error(attrParms.id ? '修改失败' : '添加失败')
  }
}

function checkRepeat(row: attrValue, index: number) {
  let isRepeat = attrParms.attrValueList.find((item: attrValue) => {
    // 将row从attrValueList取出判断
    if (row != item) {
      return row.valueName === item.valueName && row.valueName !== ''
    }
  })
  if (isRepeat) {
    attrParms.attrValueList.splice(index, 1)
    ElMessage.warning('该属性值已存在')
  }
}
</script>

<style scoped></style>
